package sync_config

import (
	"encoding/json"
	"errors"
	"news_for_deepseek_interface/logger"
	"news_for_deepseek_interface/model"
	"news_for_deepseek_interface/model/sync"
	"news_for_deepseek_interface/project/rabbitmq"
	"strconv"
	"strings"
	"time"
)

type SyncMessage struct {
	StartId            int
	Number             int
	TypeClassifyId     int
	BusinessClassifyId int
	Ids                []int
	Hour               int
	Type               int
}

func (p *SyncMessage) createLog() (id int, err error) {
	db := model.GetInstance().DB

	var idsStr = ""
	for _, id := range p.Ids {
		idsStr += strconv.Itoa(id) + ","
	}

	idsStr = strings.Trim(idsStr, ",")

	// 创建记录并获取ID
	syncLogsModel := sync.SyncLogsModel{
		Date:               time.Now(),
		TypeClassifyId:     p.TypeClassifyId,
		BusinessClassifyId: p.BusinessClassifyId,
		TotalNum:           len(p.Ids),
		Ids:                idsStr,
		Type:               p.Type,
		CreatedAt:          time.Now(),
		UpdatedAt:          time.Now(),
	}

	if err = db.Create(&syncLogsModel).Error; err != nil {
		return 0, err
	}

	return syncLogsModel.Id, nil
}

// 根据条件抽取id
func (p *SyncMessage) getIds() (ids []int, err error) {

	where := map[string]interface{}{}

	if p.TypeClassifyId != 0 {
		where["type_classify_id"] = p.TypeClassifyId
	}

	if p.BusinessClassifyId != 0 {
		where["business_classify_id"] = p.BusinessClassifyId
	}

	if err = model.GetInstance().DB.
		Model(&model.NewsModel{}).
		Where(where).
		Where("id > ?", p.StartId).
		Where("sync_status = 0").
		Order("id asc").
		Limit(p.Number).
		Pluck("id", &ids).Error; err != nil {
		return
	}

	return
}

// 同步文章
func (p *SyncMessage) SyncNews() (err error) {

	//取执行的知识库id
	ids, err := p.getIds()
	if err != nil {
		return err
	}

	//需要生产的知识库id
	p.Ids = ids

	if len(ids) == 0 {
		return errors.New("没有能同步的文章, 请检查同步配置")
	}

	//判断是最后一条 回到初始状态
	startId := ids[len(ids)-1] + 1
	var newsModel model.NewsModel
	model.GetInstance().DB.Model(&model.NewsModel{}).Where("id = ?", ids[len(ids)-1]).Order("id DESC").First(&newsModel)
	if startId > newsModel.Id {
		startId = 0
	}

	model.GetInstance().DB.Model(&sync.SyncConfigModel{}).Debug().
		Where("id = ?", 1).Updates(map[string]interface{}{
		"start_id":   startId,
		"updated_at": time.Now(),
	})

	id, err := p.createLog()
	if err != nil {
		logger.Error("创建同步文章记录失败：" + err.Error())
		return err
	}

	message := rabbitmq.SyncNewsMessage{
		Ids:        ids,
		LogId:      id,
		Categories: []string{"c263efbcc73947339beb94afe5bb54ae"},
		CoverImg:   "group1/M00/02/CF/CgoRDGaXa4GANNDnAAEHx9EdlUU393.jpg",
	}

	messageBytes, err := json.Marshal(message)
	if err != nil {
		logger.Error("发送同步文章序列化消息失败：" + err.Error())
		return err
	}

	// 发送消息到 RabbitMQ
	if err := rabbitmq.Publish(
		rabbitmq.SyncConfig.ExchangeName,
		rabbitmq.SyncConfig.RoutingKey,
		messageBytes,
	); err != nil {
		logger.Error("发送同步文章MQ消息失败：" + err.Error())
		return err
	}

	return nil
}
